<template>
  <div class="container">
    <div style="background-color: #f6f6f6;height: 70px;">
      <div style="margin: 0 auto;width: 50%; height:100%; display: flex;align-items: center">
        <img src="@/assets/imgs/logo.png" alt="" style="width: 50px">
        <span style="font-weight: bold;font-size: 24px;margin-left: 5px">文艺共鸣</span>
      </div>
    </div>
    <div
        style="margin: 0 auto;width: 50%;height: calc(100vh - 70px); display: flex; grid-gap:20px; align-items: center">
      <div style="flex: 1">
        <img style="width: 100%" src="@/assets/imgs/background.webp" alt="">
      </div>
      <div style="flex: 1">
        <div style="width: 350px; padding: 50px 30px; background-color: #f6f6f6; border-radius: 5px;">
          <div style="text-align: center; font-size: 20px; margin-bottom: 30px; color: #333">欢 迎 登 录</div>
          <el-form :model="form" :rules="rules" ref="formRef">
            <el-form-item prop="username">
              <el-input prefix-icon="el-icon-user" placeholder="请输入账号" v-model="form.username"></el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input auto-complete="new-password" prefix-icon="el-icon-lock" placeholder="请输入密码" show-password
                        v-model="form.password"></el-input>
            </el-form-item>
            <el-form-item prop="role">
              <el-select style="width: 100%" v-model="role">
                <el-option value="USER" label="普通用户"></el-option>
                <el-option value="ADMIN" label="管理员"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button style="width: 100%; background-color: #333; border-color: #333; color: white" @click="login">登
                录
              </el-button>
            </el-form-item>
            <div style="display: flex; align-items: center">
              <div style="flex: 0.5; text-align: left">
                <a type="text" @click="openPasswordDialog()" style="cursor: pointer">忘记密码</a>
              </div>
              <div style="flex: 0.5; text-align: right">
                还没有账号？请 <a href="/register">注册</a>
              </div>
            </div>
            <div style="display: flex; align-items: center;margin-top: 10px">
              <div style="flex: 0.5;text-align: left;">
                <a type="text" @click="openLoginDialog()" style="cursor: pointer">验证码登录</a>
              </div>
            </div>
          </el-form>
        </div>
      </div>
    </div>
    <div>
      <el-dialog :visible.sync="passwordVis" title="忘记密码" width="30%">
        <el-form :model="passwordForm" :rules="passwordRules" ref="rulePasswordFormRef" label-width="80px"
                 style="padding: 0 20px"
                 status-icon>
          <el-form-item label="邮箱" prop="email">
            <div style="display: flex; width: 100%">
              <el-input placeholder="请输入邮箱" v-model="passwordForm.email"
                        autocomplete="off" clearable></el-input>
            </div>
          </el-form-item>
          <el-form-item label="验证码" prop="emailCode">
            <div style="display: flex; width: 100%">
              <el-input style="flex: 1" v-model="passwordForm.emailCode" clearable></el-input>
              <el-button style="width: 120px; margin-left: 5px" @click="sendEmail" :disabled="time > 0">点击发送<span
                  v-if="time">（{{ time }}）</span></el-button>
            </div>
          </el-form-item>
          <span style="display: flex;justify-content: center;margin-top: 10px">
        <el-button @click="passwordVis = false">取消</el-button>
        <el-button type="primary" @click="resetPassword">
          确认
        </el-button>
      </span>
        </el-form>
      </el-dialog>
      <el-dialog :visible.sync="loginVis" title="验证码登录" width="30%">
        <el-form :model="passwordForm" :rules="passwordRules" ref="rulePasswordFormRef" label-width="80px"
                 style="padding: 0 20px"
                 status-icon>
          <el-form-item label="邮箱" prop="email">
            <div style="display: flex; width: 100%">
              <el-input placeholder="请输入邮箱" v-model="passwordForm.email"
                        autocomplete="off" clearable></el-input>
            </div>
          </el-form-item>
          <el-form-item label="验证码" prop="emailCode">
            <div style="display: flex; width: 100%">
              <el-input style="flex: 1" v-model="passwordForm.emailCode" clearable></el-input>
              <el-button style="width: 120px; margin-left: 5px" @click="sendEmail" :disabled="time > 0">点击发送<span
                  v-if="time">（{{ time }}）</span></el-button>
            </div>
          </el-form-item>
          <span style="display: flex;justify-content: center;margin-top: 10px">
        <el-button @click="loginVis = false">取消</el-button>
        <el-button type="primary" @click="loginByEmailCode">
          确认
        </el-button>
      </span>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script>
export default {
  name: "Login",
  data() {
    return {
      role: 'USER',
      form: {},
      rules: {
        username: [
          {required: true, message: '请输入账号', trigger: 'blur'},
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
        ]
      },
      passwordForm: {},
      passwordRules: {
        email: [
          {required: true, message: "请输入邮箱", trigger: "blur"}
        ],
        emailCode: [
          {required: true, message: "请输入验证码", trigger: "blur"},
        ],
      },
      passwordVis: false,
      loginVis:false,
      time: 0,
      intervalId: null,
      type:""
    }
  },
  created() {

  },
  methods: {
    login() {
      this.$refs['formRef'].validate((valid) => {
        if (valid) {
          // 验证通过
          this.$request.post('/login', {
            username:this.form.username,
            password:this.form.password,
            role:this.role
          }).then(res => {
            if (res.code === '200') {
              localStorage.setItem("xm-user", JSON.stringify(res.data))  // 存储用户数据
              this.$message.success('登录成功')
              setTimeout(() => {
                if (res.data.role === "ADMIN") {
                  this.$router.push('/home')//跳转后台
                  location.href = '/home'
                } else {
                  this.$router.push("/front/home")//跳转前台
                  location.href = '/front/home'
                }
              }, 500)
            } else {
              this.$message.error(res.msg)
            }
          })
        }
      })
    },
    openPasswordDialog() {
      this.passwordVis = true
      this.type="RESETPASSWORD"
    },
    openLoginDialog() {
      this.loginVis = true
      this.type="LOGIN"
    },
    times() {
      // 清除之前的定时器
      if (this.intervalId) {
        clearInterval(this.intervalId);
      }
      this.time = 60; // 重置倒计时时间
      this.intervalId = setInterval(() => {
        if (this.time > 0) {
          this.time--;
        }
      }, 1000);
    },
    sendEmail() {
      const reg = /^\w+((.\w+)|(-\w+))@[A-Za-z0-9]+((.|-)[A-Za-z0-9]+).[A-Za-z0-9]+$/
      if (!reg.test(this.passwordForm.email)) {  // test可以校验你的输入值
        this.$message.warning("请输入合法的邮箱")
        return
      }
      this.$request.get("/email", {
        params: {
          email: this.passwordForm.email,
          type: this.type,
        }
      }).then(res => {
        if (res.code === '200') {
          this.times()  // 倒计时
          this.$message.success('发送成功，有效期5分钟')
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    resetPassword() {
      this.$refs["rulePasswordFormRef"].validate(valid => {
        if (valid) {
          this.$request.put("/password/reset", {
            role:this.role,
            emailCode:this.passwordForm.emailCode,
            email:this.passwordForm.email
          }).then(res => {
            if (res.code === '200') {
              this.$message.success('重置成功，您的密码为:123456')
              this.passwordVis = false
            } else {
              this.$message.error(res.msg)
            }
          })
        }
      })
    },
    loginByEmailCode(){
      this.$refs["rulePasswordFormRef"].validate(valid => {
        if (valid) {
          this.$request.post("/loginByEmailCode", {
            role:this.role,
            emailCode:this.passwordForm.emailCode,
            email:this.passwordForm.email
          }).then(res => {
            if (res.code === '200') {
              localStorage.setItem("xm-user", JSON.stringify(res.data))  // 存储用户数据
              this.$message.success('登录成功')
              setTimeout(() => {
                if (res.data.role === "ADMIN") {
                  this.$router.push('/home')//跳转后台
                  location.href = '/home'
                } else {
                  this.$router.push("/front/home")//跳转前台
                  location.href = '/front/home'
                }
              }, 500)
            } else {
              this.$message.error(res.msg)
            }
          })
        }
      })
    }
  }
}
</script>

<style scoped>
.container {
  height: 100vh;
  overflow: hidden;
  background-color: white;

}

a {
  color: #2a60c9;
}
</style>